#!/usr/bin/env python

import web
import os
import config
from log import log
from base import adminAction
from model.news import news

'''
Admin controller: producing news administration views.
'''
class newsAction(adminAction):
    def __init__(self, name = 'News Administration'):
        adminAction.__init__(self, name)


    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'delete':
            return self.delete()
        elif name == 'add':
            return self.add()
        elif name == 'edit':
            return self.edit()
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'modify':
            return self.modify()
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        newsObj = news()
        listData = newsObj.getOne('COUNT(*) AS `total`',condition)
        totalCount = listData['total']
        newsList = newsObj.getList('*', condition, 'id desc', str(offset) + ',' + str(count))
        pageString = self.getPageStr('/admin/news/list', page, count, totalCount)
        self.privData['NEWS_LIST'] = newsList
        self.privData['PAGE_STRING'] = pageString
        self.privData['STATUS_LIST'] = { 1:'Published', 0: 'Draft'}
        return self.display('newsList')

    def delete(self):
        inputParams = self.getInput()
        if not inputParams.has_key('id') :
            return self.error('News not exists!')
        id=inputParams['id']
        condition={'id':str(id)}
        result=news().delete(condition)
        if result:
            return self.success(msg='Delete successfully!', url='/admin/news/list')
        else:
            return self.error(msg='Delete failed!')

    def add(self):
        self.privData['STATUS_LIST'] = { 1:'Published', 0: 'Draft'}
        return self.display('newsAdd')
    
    def modify(self):
        userInput= self.getInput()

        data={
            'content':self.htmlunquote(userInput['content']),
            'name':userInput['name'],
            'status':userInput['status'],
            'category':userInput['category'],
        }

        condition = {'id':userInput['id']}
        status = news().update(data, condition)
        if status:
            return self.success('Modify successfully!', url='/admin/news/list')
        else:
            return self.error('Modify failed!')

    def edit(self):
        inputParams = self.getInput()
        if not inputParams.has_key('id') :
            return self.error('News not exists!')
        id=inputParams['id']
        condition={'id':str(id)}
        atl= news().getOne('*',condition)
        self.privData['STATUS_LIST'] = { 1:'Published', 0: 'Draft'}
        self.privData['NEWS_CONTENT'] = atl['content']
        self.privData['NEWS_ID'] = atl['id']
        self.privData['NEWS_CATEGORY'] = atl['category']
        self.privData['NEWS_NAME'] = atl['name']
        self.privData['NEWS_STATUS'] = atl['status']
        return self.display('newsEdit')


    def save(self):
        import time

        userInput= self.getInput()
        currentDate = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())

        thumbnail = userInput['thumbnail']
        if not thumbnail or not os.path.exists(config.UPLOAD_DIR + thumbnail):
            thumbnail = config.ROOT_DIR + 'static/images/question.png'
        blob = None

        try:
            from utils import imageHelper 
            helper = imageHelper(thumbnail)
            info = self.findModule('user', 'news')['thumbnail']
            blob = helper.thumbnail(info['xres'], info['yres'], info['quality'])
        except:
            log.warn('Retrieving thumbnail from %s failed' % thumbnail)

        data = {
            'content':      self.htmlunquote(userInput['content']),
            'name':         userInput['name'],
            'createTime':   currentDate,
            'status':       userInput['status'],
            'category':     userInput['category'],
            'thumbnail':    buffer(blob),
        }

        status = news().insert(data)
        if not status:
            return self.error('Save failed!')

        return self.success('Save successfully!', url='/admin/news/list')
